//
//  BookDetailShowViewController.m
//  LiteraryTune
//
//  Created by 神州四达 on 2018/1/19.
//  Copyright © 2018年 cxd. All rights reserved.
//

#import "BookDetailShowViewController.h"
#import "TopBookListTableViewCell.h"
#import "IntroductBookTableViewCell.h"
#import "CatalogueTableViewCell.h"
#import "ChapterTableViewCell.h"
#import "HasMoreTableViewCell.h"
#import "BookDetailModel.h"
#import "BookReadVC.h"
#import "LoginViewController.h"
#import <QuickLook/QuickLook.h>

@interface BookDetailShowViewController () <UITableViewDelegate,UITableViewDataSource,QLPreviewControllerDelegate,QLPreviewControllerDataSource>

@property (nonatomic, strong)UITableView *tableView;
//数据源
@property (nonatomic, strong)BookDetailModel *dataModel;

@property (strong, nonatomic)QLPreviewController *previewController;

@property (copy, nonatomic)NSURL *fileURL; //文件路径


@end

@implementation BookDetailShowViewController

#pragma mark -- 书籍列表

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self getNetData];
    self.previewController  =  [[QLPreviewController alloc]  init];
    self.previewController.dataSource  = self;
//    [self getBookChapter];
    [self buildUI];
}

- (void)getNetData {
    [CXDNetHelp getRequestWithURLString:[NSString stringWithFormat:@"%@%@",BookDetailURL,_bookId] parameters:nil success:^(id  _Nullable responseObject) {
//        NSLog(@"%@",responseObject);
        _dataModel = [BookDetailModel yy_modelWithJSON:responseObject];
        [self.tableView reloadData];
    } failure:^(NSError * _Nullable error) {
        
    }];
}
- (void)pdfBtnOnClick
{
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSString *urlStr =[NSString stringWithFormat:@"%@%@",RootHomeURL,_dataModel.url];
    NSString *fileName = [urlStr lastPathComponent]; //获取文件名称
    NSURL *URL = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    //判断是否存在
    if([self isFileExist:fileName]) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
        self.fileURL = url;
        self.previewController.title = _dataModel.news_tit;
        [self presentViewController:self.previewController animated:YES completion:nil];
        //刷新界面,如果不刷新的话，不重新走一遍代理方法，返回的url还是上一次的url
        [self.previewController refreshCurrentPreviewItem];
    }else {
        [SVProgressHUD showWithStatus:@""];
        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
            
        } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
            return url;
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            
            [SVProgressHUD dismiss];
            self.fileURL = filePath;
            [self presentViewController:self.previewController animated:YES completion:nil];
            //刷新界面,如果不刷新的话，不重新走一遍代理方法，返回的url还是上一次的url
            [self.previewController refreshCurrentPreviewItem];
        }];
        [downloadTask resume];
    }
  
}


- (void)buildUI {
    [self.view addSubview:self.tableView];
}

#pragma mark - event resposen
//阅读
- (void)readBtnClickAction {
    if (![CXDHelper getUserLoginStatus] && [NSUserDefaults.standardUserDefaults boolForKey:K_NeedLogin]) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }else {
        
        [self pdfBtnOnClick];
        
    }
}
//判断文件是否已经在沙盒中存在
-(BOOL) isFileExist:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    return result;
}
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
    return 1; //需要显示的文件的个数
}
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    //返回要打开文件的地址，包括网络或者本地的地址
    NSURL * url = self.fileURL;
    return url;
}

//加入书架
- (void)addBtnAction {
    if (![CXDHelper getUserLoginStatus] && [NSUserDefaults.standardUserDefaults boolForKey:K_NeedLogin]) {
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:loginVC animated:YES];
    }else {
        [CXDNetHelp getRequestWithURLString:[NSString stringWithFormat:@"%@username/%@/id/%@",AddToShelfURL,[CXDHelper getUserAccountName],_dataModel.bookID] parameters:nil success:^(id  _Nullable responseObject) {
            if ([responseObject isEqualToString:@"1"]) {
                [CXDNoticeView showNoticeViewWithString:@"成功加入书架"];
            }else {
                [CXDNoticeView showNoticeViewWithString:@"图书已经收藏过"];
            }
        } failure:^(NSError * _Nullable error) {
            
        }];
    }
}

#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 200;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TopBookListTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([TopBookListTableViewCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([IntroductBookTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([IntroductBookTableViewCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CatalogueTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([CatalogueTableViewCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ChapterTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([ChapterTableViewCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([HasMoreTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([HasMoreTableViewCell class])];
    }
    return _tableView;
}

#pragma mark - 协议实现
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            TopBookListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([TopBookListTableViewCell class])];
            [cell.bookImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",RootHomeURL,_dataModel.spic]]];
            cell.titleLabel.text = _dataModel.news_tit;
            cell.authLabel.text = _dataModel.author;
            cell.QrimageView.image = [XinxinTools QRCodeImageWithString:[NSString stringWithFormat:@"%@%@",RootHomeURL,_dataModel.url] size:CGSizeMake(100, 100)];
//            [cell.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",QRCodeURL,_bookId]]]];
            [cell.readBtn addTarget:self action:@selector(readBtnClickAction) forControlEvents:UIControlEventTouchUpInside];
            [cell.addBtn addTarget:self action:@selector(addBtnAction) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
        IntroductBookTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([IntroductBookTableViewCell class])];
        cell.contentLab.text = _dataModel.jianjie;
        return cell;
    }
    if (indexPath.row == 0) {
        CatalogueTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CatalogueTableViewCell class])];
        return cell;
    }else if (indexPath.row == 9) {
        HasMoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HasMoreTableViewCell class])];
        return cell;
    }
    ChapterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ChapterTableViewCell class])];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row ==0) {
            return 600;
        }
        return UITableViewAutomaticDimension;
    }
    return 50;
}

@end
